/**
 * Copyright 2012 Tautvydas Andrikys
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */
package inet.app.vod.facebook;

import android.webkit.WebView;

/**
 * Used in Like view to manage web requests/responses
 */
public class WebViewClient extends android.webkit.WebViewClient {

	/**
	 * @var do we need to click on button after loading
	 */
	private boolean click = false;

	/**
	 * Url loading or not for like button
	 * 
	 * @param view
	 * @param url
	 * 
	 * @return do we need to load
	 */
	@Override
	public boolean shouldOverrideUrlLoading(WebView view, String url) {
		if (url.equals("about:blank")) {
			return false;
		}
		view.loadUrl(url);
		return true;
	}

	/**
	 * After page loading is finished we can click on button if needed
	 * 
	 * @param view
	 * @param url
	 */
	@Override
	public void onPageFinished(WebView view, String url) {
		super.onPageFinished(view, url);
		if (click) {
			this.click = false;
			view.loadUrl("javascript:var evt = document.createEvent('MouseEvents'); evt.initMouseEvent('click');"
					+ "document.getElementsByTagName("
					+ "document.getElementsByTagName('A').length > 0 ? 'A' : 'I'"
					+ ").item(0).dispatchEvent(evt);");
		}
	}

	/**
	 * Sets that we need to click on like button after loading page
	 * 
	 * @param click
	 */
	public void setClickAfterLoad(boolean click) {
		this.click = click;
	}

}
